<template>
    <div>
        <div class="mt-6">
        <h3 class="text-lg">{{ $t("基本属性") }}</h3>
        <el-card class="mt-5" shadow="always">
          <el-form
            ref="createFormRef"
            label-position="top"
            :model="cardInfo"
            :rules="rules"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('卡片额度')" prop="total_amount">
                  <el-input
                    v-model="cardInfo.total_amount"
                    :placeholder="$t('请输入额度')"
                    class="input-with-select customInput"
                    @input="handleTotalAmountChange"
                    size="large"
                    type="number"
                  >
                    <template #append>
                      <el-select v-model="cardInfo.currency" :placeholder="$t('币种')" @change="handleCurrencyChange" style="width: 115px" size="large">
                        <el-option
                            v-for="item in state.cardsCurrencyList"
                            :key="item.currency"
                            :label="item.currency"
                            :value="item.currency"
                          >
                          </el-option>
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('卡片别名')" prop="nick_name">
                  <el-input
                    v-model="cardInfo.nick_name"
                    size="large"
                    :placeholder="$t('请输入卡别名')"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('姓氏')" prop="last_name">
                  <el-input
                    v-model="cardInfo.last_name"
                    size="large"
                    :placeholder="$t('请输入姓氏')"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('名字')" prop="first_name">
                  <el-input
                    v-model="cardInfo.first_name"
                    size="large"
                    :placeholder="$t('请输入名字')"
                  ></el-input>
                </el-form-item>
              </el-col>

            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('手机号')" prop="mobile">
                   <el-input
                      v-model="cardInfo.mobile"
                      :placeholder="$t('输入手机号码')"
                      size="large"
                      type="number"
                      class="customInput"
                    >
                    <template #prepend>
                      <el-input
                        class="customInputWrap"
                        v-model="cardInfo.area_code"
                        :placeholder="$t('区号')"
                        style="width: 80px"
                        size="large"
                        type="number"
                      >
                      </el-input>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('邮箱')" prop="email">
                  <el-input
                    v-model="cardInfo.email"
                    size="large"
                    :placeholder="$t('请输入邮箱地址')"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
      <div class="mt-6">
        <h3 class="mb-5 text-lg">{{ $t("扣款方式") }}</h3>
        <el-row :gutter="20"> 
          <el-col :span="24">
            <el-card>
              <el-row :gutter="30">
                <el-col :span="12">
                  <div class="detailRow">
                    <p class="rowName">{{ $t("资产") }}</p>
                       <p class="rowValue">
                      <el-select v-model="state.currencyInfo" class="customSelect" @change="selectBalance" v-if="state.currencyList.length>1">
                          <el-option
                            v-for="item in state.currencyList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                      </el-select>
                      <p v-else>{{ state.currencyInfo }}</p>
                    </p>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="detailRow">
                    <p class="rowName">{{ $t("消耗金额") }}</p>
                    <!-- 输入的总额度 + 总额度*费率*币种价格 -->
                    <p class="rowValue">
                      {{
                        cardInfo.total_amount ?
                        cardInfo.asset_type == "balance"
                          ? truncateDecimals(
                              state.totalPrice,
                              2
                            )
                          : truncateDecimals(
                              state.totalPrice,
                              8
                            ) : 0
                      }}
                      {{ state.currency }}
                    </p>
                  </div>
                </el-col>
              </el-row>
              <el-row :gutter="30"> 
                <el-col :span="12">
                  <div class="detailRow">
                    <p class="rowName">{{ $t("汇率") }}</p>
                    <!--  1 + 选择的币种【currency】  ≈ 币种价格获取的汇率 + 选择的资产【currency】 -->
                    <p class="rowValue">
                      {{
                        state.currencyInfo ? 
                        `1 ${cardInfo.currency} ≈ ${state.price} ${state.currency}` : "--"
                      }}
                    </p>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="detailRow">
                    <p class="text-sm rowName">
                      {{ `${$t("手续费")}` }}{{
                        `(${state.card_rate ? state.card_rate * 100 : 0}%  ) `
                      }}</p>
                    <p class="rowValue">
                      <span v-if="state.currencyInfo">{{
                        state.card_rate && cardInfo.total_amount ? cardInfo.asset_type == "balance"  ? truncateDecimals(cardInfo.total_amount * state.card_rate * state.price, 2) : truncateDecimals(cardInfo.total_amount * state.card_rate * state.price, 8) : 0
                      }}
                      {{ state.currency }}</span>
                      <span v-else>--</span>
                      
                    </p>
                  </div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
        <div class="flex items-center justify-center">
        <div
          size="large"
          type="danger"
          class="h-10 mt-10 w-36 btn"
          @click="addCardSave(createFormRef)"
          v-loading="btnLoading"
        >
          {{ $t("创建卡片") }}
        </div>
      </div>
      </div>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted,computed,watch } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import {
  AddCard,
  GetCardsConfig,
  GetCardsBalance,
  GetCardsPrice,
  GetCardsCurrency,
} from "@/api/card";
import { ElMessage } from "element-plus";
import { truncateDecimals } from "@/utils/utils";
const router = useRouter();

const props = defineProps({
    cardTypeInfo: {
        type: Object,
        default:()=>{}
    },
    balanceInfo: {
        type: Object,
        default:()=>[]
    },
    coinsInfo: {
        type: Object,
        default:()=>[]
    }
})

const createFormRef = ref(null);
const btnLoading = ref(false);

const state = reactive({
  asset_type: "balance",
  totalPrice: 0,
  price: 0, // 选择币种价格
  card_rate: 0, // 汇率
  currencyType: "currency", //货币类型
  currencyList: [],
  currencyInfo: "",
  currency: "",
});

const cardInfo = reactive({
  category_id: "",
  total_amount: "",
  nick_name: "",
  first_name: "",
  mobile: "",
  email: "",
  currency: "",
  asset_type: "balance",
  last_name:"",
  asset_currency: "",
});

const lsLocale = localStorage.getItem('locale') || ''
const currentLanguage = ref("")
if (lsLocale) {
  currentLanguage.value = JSON.parse(lsLocale)?.locale
}

const cardInformation = async()=>{
      // 判断如果扣款方式为balance，则取他相应的资产列表
  if (props.cardTypeInfo.asset_type == "balance") {
    state.currencyList = [];
    if (props.balanceInfo.length > 0) {
      state.currencyList = props.balanceInfo.map((item) => {
        return {
          label: item.amount + " " + item.currency,
          value: item.amount + " " + item.currency,
        };
      });
    }
  }
  // 判断如果扣款方式为crypto，则取他相应的资产列表（coins）
  if (props.cardTypeInfo.asset_type == "crypto") {
    state.currencyList = [];
    if (props.coinsInfo.length > 0) {
      state.currencyList = props.coinsInfo.map((item) => {
        return {
          label: item.amount + " " + item.currency,
          value: item.amount + " " + item.currency,
        };
      }); // 币种选项
    }
  }
  state.card_rate = props.cardTypeInfo.card_rate
  // 获取当前卡片的币种，即卡片额度右侧的币种
  await getCardsCurrency(); // 获取卡片币种
  if (props.cardTypeInfo.asset_type == "balance" && props.balanceInfo.length > 0) {
    amountInfo(props.balanceInfo);
  }
  if (props.cardTypeInfo.asset_type == "crypto" && props.coinsInfo.length > 0) {
    amountInfo(props.coinsInfo);
  }
  // 默认选用第一个币种
  const currency = state.currencyInfo.split(" ")[1] || "";
  await getCardPrice(currency, true); // 获取币种金额，即下方资产下拉，多条展示下拉，一条不展示下拉
}
onMounted(() => {
    cardInformation()
})

// 邮箱验证
const checkEmail = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t("邮箱不能为空")));
  } else {
    const emailRegExp =
      /^([a-zA-Z0-9_\.-]+)@([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})$/;
    if (emailRegExp.test(value)) {
      callback();
    } else {
      return callback(new Error(t("请输入正确的邮箱")));
    }
  }
};

// 卡额度验证，必须大于1
const checkTotalAmount = (rule, value, callback) => {
  if (!value) {
    return callback(new Error(t("卡片额度不能为空")));
  } else {
    let money = Number(cardInfo.total_amount) * state.price;
    if (value <= 1) {
      return callback(new Error(t("卡片额度必须大于1")));
    } else if (money > Number(state.currencyInfo.split(" ")[1])) {
      return callback(
        new Error(`${t("扣款币种")} ${state.currency} ${t("余额不足")}`)
      );
    } else {
      callback();
    }
  }
};

// 规则验证
const rules = reactive({
  total_amount: [
    { required: true, message: t("请输入卡片额度"), trigger: "blur" },
    { validator: checkTotalAmount, trigger: "blur" },
  ],
  nick_name: [
    { required: true, message: t("请输入卡片别名"), trigger: "blur" },
  ],
  last_name: [
    { required: true, message: t("请输入姓氏"), trigger: "blur" },
  ],
  first_name: [
    { required: true, message: t("请输入名字"), trigger: "blur" },
  ],
  mobile: [
    { required: true, message: t("请输入手机号"), trigger: "blur" },
    { min: 6, max: 16, message: t("请输入6-16位的数字"), trigger: "blur" },
  ],
  email: [
    { required: true, message: t("请输入邮箱"), trigger: "blur" },
    { validator: checkEmail, trigger: "change" },
  ],
});


// 获取资产模块数据
const amountInfo = (info) => {
  let amountInfo = [];
  // 根据资产类型使用对应列表数据，默认选中第一条数据
  amountInfo = info.filter((item) => {
    if (item.currency === cardInfo.currency) {
      return item;
    }
  });
  // 默认第一条
  state.currencyInfo =
    amountInfo.length < 1
      ? `${info[0].amount} ${info[0].currency} `
      : `${amountInfo[0].amount} ${amountInfo[0].currency}`;
  state.currency = state.currencyInfo.split(" ")[1] || "";
};

// 选择币种
const handleCurrencyChange = async (val) => {
  // 选择币种切换下方资产数据
  const { balance, coins } = await GetCardsBalance();
  if (balance.length > 0) {
    amountInfo(balance);
  } else {
    amountInfo(coins);
  }
};

// 选择资产
const selectBalance = async (val) => {
  const currency = val.split(" ")[1] || "";
  getCardPrice(currency); // 获取币种价格
};

// 获取币种价格
const getCardPrice = async (currency, isTrue) => {
  if (cardInfo.currency) {
    let query = {
      from_currency: cardInfo.currency, //币种
      to_currency: currency,
      to_type: props.cardTypeInfo.asset_type == "balance"  ? "currency" : "coin", //根据资产类型判断穿什么字段
    };
    try {
      const { price } = await GetCardsPrice(query);
      state.price = price;
      state.currency = state.currencyInfo.split(" ")[1] || ""; // 汇率后方的币种

      // 初始化进来不校验
      if (!isTrue && cardInfo.total_amount !== "") {
        createFormRef.value.validateField("total_amount");
      }
      // 总额度*汇率 虚拟资产保留6位小数,货币资产保留2位小数
      if (cardInfo.total_amount !== "") {
        state.totalPrice =
          (cardInfo.total_amount * state.price) +
            (cardInfo.total_amount * state.card_rate *
            state.price) || 0;
      } else {
        state.totalPrice = 0;
      }
    } catch {
      // loading.value = false;
    }
  }
};

// 输入卡额度
const handleTotalAmountChange = (val) => {
  let index = val.indexOf("."); // 只能输入正整数
  if(index) {
    cardInfo.total_amount = cardInfo.total_amount.split(".")[0];
  } else {
    cardInfo.total_amount = val;
  }
  // 输入的总额度*币种价格 + 总额度*费率*币种价格 虚拟资产保留6位小数,货币资产保留2位小数
  let price = ((val * state.price) + (val * state.card_rate * state.price)) ;
  state.totalPrice = price;
};

// 创建卡片
const addCardSave = (formRef) => {
  if (!formRef) return;
  formRef.validate(async (valid, fields) => {
    if (valid) {
      if (!props.cardTypeInfo.category_id) {
        ElMessage.error(t("请选择卡类型"));
      } else {
        if (!cardInfo.area_code) {
          ElMessage.error(t("请填写区号"));
        } else {
          try {
            btnLoading.value = true;
            cardInfo.asset_currency = state.currency;
            cardInfo.category_id = props.cardTypeInfo.category_id;
            console.log(cardInfo,'cardInfo')
            const data = await AddCard(cardInfo);
            btnLoading.value = false;
            ElMessage({
              type: "success",
              message: data.offline
                ? t(
                    "卡片创建成功，进入审核阶段，审核通过后将激活卡片并可以进行使用"
                  )
                : t("创建卡片成功"),
            });
            router.replace({
              path: "/card/management",
            });
          } catch {
            btnLoading.value = false;
          }
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 获取币种，默认选中第一条
const getCardsCurrency = async () => {
  try {
    const { cards_currency } = await GetCardsCurrency({
      category_id: props.cardTypeInfo.category_id,
    });
    state.cardsCurrencyList = cards_currency;
    cardInfo.currency = state.cardsCurrencyList[0].currency;
  } catch {}
};


</script>
<style lang="scss" scoped>
.detailRow {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0.5rem;

  .rowName {
    min-width: 30%;
    flex-shrink: 0;
    display: inline-block;
  }
  .selectName {
    min-width: 10%;
    text-align: center;
    flex-shrink: 0;
    display: inline-block;
  }

  .rowValue {
    display: inline-block;
    word-break: break-all;
    text-align: right;
  }
}
.hoverStyle:hover {
  background-color: #f4e1e1;
  border-radius: 5px;
}
.active {
  background-color: #ebc9c9;
  border-radius: 5px;
}
.btn {
  text-align: center;
  line-height: 40px;
  background: #e54c5f;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
}
.selectIcon {
  color: #e54c5f;
  font-size: 24px;
}

.selectedType {
  border: 1px solid #e54c5f;
  border-radius: 5px;
}
</style>